package com.yys.zproject.controller.user;

import com.yys.zproject.entity.UserEntity;
import com.yys.zproject.service.impl.UserServiceimpl;
import com.yys.zproject.utils.JspPageUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author 14343
 * @version 1.0
 * @date 2025/9/23 20:54
 * @description: TODO
 */
@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //TODO: 用户登录逻辑
        System.out.println("用户登录功能...");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String captcha=req.getParameter("captcha");
        //FIXME: 验证码校验逻辑
        HttpSession captchaSession = req.getSession();
        String captchaCode = (String) captchaSession.getAttribute("captcha");
        //区分大小写
        if (!captchaCode.equals(captcha))
        {
            JspPageUtils.forwardtoPageAndTipMsg(req, resp, "验证码错误", "/login.jsp");
            //一次性的验证码用完就删
            captchaSession.removeAttribute("captcha");
            return;
        }


        UserServiceimpl userService = new UserServiceimpl();

        UserEntity loginUser = userService.login(username,password);

        if (loginUser!=null)
        {
            HttpSession sessions = req.getSession();
            sessions.setAttribute("loginUser",loginUser);
            resp.sendRedirect("/zpro/index.jsp");

        }
        else
        {
            JspPageUtils.forwardtoPageAndTipMsg(req, resp, "用户名或密码错误", "/login.jsp");

        }

    }

}
